package com.daocao.hua.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.daocao.hua.R;
import com.daocao.hua.activity.HelpActivity;
import com.daocao.hua.activity.LookPayProcessActivity;
import com.daocao.hua.api.callback.BannerContract;
import com.daocao.hua.api.requestInfo.BannerRequest;
import com.daocao.hua.constant.Const;
import com.daocao.hua.event.BannerEvent;
import com.daocao.hua.event.OnRepayEventMsg;
import com.daocao.hua.event.OnRepayFailEventMsg;
import com.daocao.hua.event.OnRepaySuccessEventMsg;
import com.daocao.hua.model.BannerModel;
import com.daocao.hua.util.StatusBarCompat;
import com.daocao.hua.util.UI;
import com.daocao.hua.view.BannerLayout;
import com.daocao.hua.view.ProportionImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by xsooy-pc on 2017/5/3.
 * 我的借款 页面
 */

public class MyLoanFragment extends BaseFragment implements View.OnClickListener, TabLayout.OnTabSelectedListener, ViewPager.OnPageChangeListener, BannerContract.View {

    private TabLayout tabLayout;
    private ViewPager viewPager;
    //    private ImageView closeBtn;
//    private RelativeLayout tip;
    private View dot;
    private BannerLayout bannerLayout;
    private String url;
    private RepayFragment repayFragment;
    private RepayRecordFragment repayRecordFragment;
    private BannerRequest api;
    private ImageButton left_img;

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_my_loan;
    }

    @Override
    protected void initView() {
        api = BannerRequest.create();
        api.attachView(this);
        tabLayout = findView(R.id.tab_layout);
        viewPager = findView(R.id.view_pager);
//        closeBtn = findView(R.id.btn_close);
        bannerLayout = findView(R.id.banner);
        left_img = findView(R.id.left_img);
//        tip = findView(R.id.rl_tip);
        repayFragment = new RepayFragment();
        repayRecordFragment = new RepayRecordFragment();
        tabLayout.addOnTabSelectedListener(this);
        viewPager.addOnPageChangeListener(this);
        left_img.setOnClickListener(this);
//        closeBtn.setOnClickListener(this);
        EventBus.getDefault().register(this);
        getBannerInfo();

        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    int height = StatusBarCompat.getStatusBarHeight(getContext());
                    if (height == 0) {
                        return;
                    }
                    left_img.setPadding(0, height, 0, 0);
                }
                setIndicator(tabLayout);
            }
        });
    }


    private void getBannerInfo() {
        api.getBanner(api.TYPE_DEAL);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.left_img:
                Intent msgIntent = new Intent(getActivity(), HelpActivity.class);
                msgIntent.putExtra("type", 0);
                startActivity(msgIntent);
                getActivity().overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;

        }
    }

    /**
     * 事件监听
     *
     * @param msg
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void repayEventBus(OnRepayEventMsg msg) {
        int type = (int) msg.getMap().get(Const.KEY.REPAY_TYPE);
        if (dot == null) {
            return;
        }
        if (type == 0) {//已还款
            dot.setVisibility(View.GONE);
        } else {//未还款
            dot.setVisibility(View.VISIBLE);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBannerEvent(BannerEvent msg) {
        if (photoUrl.size() == 0)
            getBannerInfo();
    }

    /**
     * 事件监听
     *
     * @param msg
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void repaySucessEventBus(OnRepaySuccessEventMsg msg) {
        tabLayout.getTabAt(1).select();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void repayFailEventBus(OnRepayFailEventMsg msg) {
        tabLayout.getTabAt(0).select();
    }

    private boolean isFirstLoad = true;

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        viewPager.setCurrentItem(tab.getPosition());
//        if (tab.getPosition() == 1 && isFirstLoad) {
//            isFirstLoad = false;
//            repayRecordFragment.setData();
//        }
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        tabLayout.getTabAt(position).select();
//        if (position == 1 && isFirstLoad) {
//            isFirstLoad = false;
//            repayRecordFragment.setData();
//        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void showError() {

    }

    @Override
    public void complete() {

    }

    @Override
    public void onRequestStart() {

    }

    private List<String> photoUrl = new ArrayList<>();

    @Override
    public void getBannerSuccess(BannerModel data) {
        if (data.getData() != null) {
            photoUrl.clear();
            for (int i = 0, bannerSize = data.getData().size(); i < bannerSize; i++) {
                photoUrl.add(data.getData().get(i).getImg());
            }
            if (data.getData().size() != 0) {
                bannerLayout.setViewUrls(photoUrl);
                bannerLayout.setOnBannerItemClickListener(new BannerLayout.OnBannerItemClickListener() {
                    @Override
                    public void onItemClick(int position) {
                        if (UI.isFastClick()) {
                            return;
                        }
                        Intent intent = new Intent(getContext(), LookPayProcessActivity.class);
                        intent.putExtra(Const.KEY.PROCESS_URL, data.getData().get(position).getData());
                        intent.putExtra("title", data.getData().get(position).getName());
                        startActivity(intent);
//                            Intent intent = new Intent(getContext(), AlipayWebViewActivity.class);
//                            intent.putExtra(Const.KEY.PROCESS_URL, "HTTPS://QR.ALIPAY.COM/FKX09479SSJHBQ3GW6UABD");
//                            intent.putExtra("title", data.getData().get(position).getName());
//                            startActivity(intent);
//                            https%3A%2F%2Fqr.alipay.com%2FFKX02840I81DJW2LBA28A4
//                            Intent intent = new Intent();
//                            intent.setAction("android.intent.action.VIEW");
//                            Uri content_url = Uri.parse("alipays://platformapi/startapp?saId=10000007&clientVersion=3.7.0.0718&qrcode=HTTPS://QR.ALIPAY.COM/FKX09479SSJHBQ3GW6UABD%3F_s%3Dweb-other");
//                            intent.setData(content_url);
//                            startActivity(intent);

                    }
                });
                if (data.getData().size() == 1) {
                    bannerLayout.stopAutoPlay();
                }
            }
        }

    }


    public class RepayPagerAdapter extends FragmentPagerAdapter {

//        String[] tabs = {"未还账单", "还款记录"};

        public RepayPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return 2;
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    if (repayFragment != null) {
                        return repayFragment;
                    }
                    return new RepayFragment();
                case 1:
                    if (repayRecordFragment != null) {
                        return repayRecordFragment;
                    }
                    return new RepayRecordFragment();
            }
            return null;
        }


    }


    public void setIndicator(TabLayout tabs) {
        RelativeLayout leftView = (RelativeLayout) getActivity().getLayoutInflater().inflate(R.layout.item_tab_left, tabs, false);
        dot = (View) leftView.findViewById(R.id.dot);
        tabs.addTab(tabs.newTab().setCustomView(leftView));
        TextView rightView = (TextView) getActivity().getLayoutInflater().inflate(R.layout.item_tab_right, tabs, false);
        tabs.addTab(tabs.newTab().setCustomView(rightView));
        viewPager.setAdapter(new RepayPagerAdapter(getFragmentManager()));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        api.detachView();
        EventBus.getDefault().unregister(this);
    }
}
